using Logic.Global;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace Core.Extension
{
    /// <summary>
    /// 移动端Touch拓展类。
    /// </summary>
    public class TouchExt : MonoBehaviour
    {
        /// 之前是否触摸开始过
        private bool IsTouchBegan => _fingerId >= 0;

        [Header("是否为2D碰撞体，false则表示使用3D碰撞检测")] public bool Is2D = true;

        [Header("当触摸开始")] public UnityEvent<Touch> onTouchBegin;

        [Header("当触摸移动")] public UnityEvent<Touch> onTouchMoved;

        [Header("当触摸结束")] public UnityEvent<Touch> onTouchEnded;

        /// 当前处于触摸中的FingerId
        private int _fingerId = -1;

        protected void Update()
        {
            foreach (var touch in Input.touches)
            {
                if (touch.phase == TouchPhase.Began && !IsTouchBegan)
                {
                    var touchWorldPos = GameCamera.Ins.gameCamera.ScreenToWorldPoint(touch.position);
                    if (Is2D)
                    {
                        RaycastHit2D hit = Physics2D.Raycast(touchWorldPos, Vector2.zero, Mathf.Infinity);
                        if (hit.collider != null && hit.collider.gameObject.Equals(gameObject))
                        {
                            _fingerId = touch.fingerId;
                            onTouchBegin?.Invoke(touch);
                        }
                    }
                    else
                    {
                        Ray ray = GameCamera.Ins.gameCamera.ScreenPointToRay(Input.mousePosition);
                        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
                        {
                            if (hit.collider != null && hit.collider.gameObject.Equals(gameObject))
                            {
                                _fingerId = touch.fingerId;
                                onTouchBegin?.Invoke(touch);
                            }
                        }
                    }
                }
                else if (touch.phase == TouchPhase.Moved && touch.fingerId == _fingerId)
                {
                    onTouchMoved?.Invoke(touch);
                }
                else if (touch.phase == TouchPhase.Ended && touch.fingerId == _fingerId)
                {
                    _fingerId = -1;
                    onTouchEnded?.Invoke(touch);
                }
            }
        }
    }
}